﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Xml;
using System.Xml.Serialization;

namespace TypeWrite.Core
{ 
    [Serializable]
    public class Settings
    {

        public static Settings Instance = null;

        static string dataPath = HttpContext.Current.ApplicationInstance.Server.MapPath("~/App_Data");
        static string filename = ConfigurationManager.AppSettings["dataFileName"];

        public static Settings Load()
        {
            Instance = new Settings();

            string dataFilePath = Path.Combine(dataPath, filename);

            if (File.Exists(dataFilePath))
            {
                XmlSerializer serializer = new XmlSerializer(typeof(Settings));
                using (var fs = new FileStream(dataFilePath, FileMode.Open))
                {
                    Instance = serializer.Deserialize(fs) as Settings;
                    fs.Flush();
                    fs.Close();
                }
            }

            return Instance;
        }
         
        public bool AllowRegistration { get; set; }

        public string DbInstance { get; set; }

        public string DbAdmin { get; set; }

        public string DbName { get; set; }

        public string DbPassword { get; set; }

        public string ConnectionString
        {
            get
            {
                return string.Format("Data Source={0};Initial Catalog={1};Persist Security Info=True;User ID={2};Password={3};", DbInstance, DbName, DbAdmin, DbPassword);
            }
        }

        public bool RequireActivation { get; set; }

        public void Save()
        {
            XmlSerializer serializer = new XmlSerializer(typeof(Settings));
            using (var fs = new FileStream(Path.Combine(dataPath, filename), FileMode.OpenOrCreate))
            {
                serializer.Serialize(fs, this);
                fs.Flush();
                fs.Close();
            }
            Trim();
        }

        private void Trim()
        {
            string serialized = string.Empty;

            using (StreamReader reader = new StreamReader(Path.Combine(dataPath, filename)))
            {
                serialized = reader.ReadToEnd();
                reader.Close();
            }

            if (serialized.EndsWith(">s>"))
            {
                using (StreamWriter writer = new StreamWriter(Path.Combine(dataPath, filename)))
                {
                    string trimmed = serialized.Replace(">s>", ">");

                    writer.Write(trimmed);
                    writer.Flush();
                    writer.Close();
                }
            }

        }

    }
}
